// app/service/system_service.js
'use strict';

const { Service } = require('egg');

class SystemService extends Service {
  // ==================== 用户管理 ====================
  
  // 获取用户列表
  async getUsers(queryParams) {
    const { ctx } = this;
    const { page = 1, limit = 20, name, email, role, status } = queryParams;
    
    try {
      // 构建查询条件
      const whereClause = {};
      
      if (name) {
        whereClause.name = {
          [ctx.app.Sequelize.Op.like]: `%${name}%`
        };
      }
      
      if (email) {
        whereClause.email = email;
      }
      
      if (role) {
        whereClause.role = role;
      }
      
      if (status) {
        whereClause.status = status;
      }
      
      // 查询数据
      const result = await ctx.model.UserModel.findAndCountAll({
        where: whereClause,
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit)
      });
      
      // 转换数据格式
      const users = result.rows.map(user => ({
        id: user.id,
        name: user.name,
        email: user.email,
        role: user.role,
        status: user.status,
        lastLoginAt: user.lastLoginAt,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt
      }));
      
      return {
        list: users,
        pagination: {
          total: result.count,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      };
    } catch (error) {
      ctx.logger.error('获取用户列表业务逻辑执行失败:', error);
      throw new Error(`获取用户列表业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 获取用户详情
  async getUser(id) {
    const { ctx } = this;
    
    try {
      const user = await ctx.model.UserModel.findByPk(id);
      
      if (!user) {
        throw new Error('用户不存在');
      }
      
      return {
        id: user.id,
        name: user.name,
        email: user.email,
        role: user.role,
        status: user.status,
        lastLoginAt: user.lastLoginAt,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt
      };
    } catch (error) {
      ctx.logger.error('获取用户详情业务逻辑执行失败:', error);
      throw new Error(`获取用户详情业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 创建用户
  async createUser(userData) {
    const { ctx } = this;
    const { name, email, password, role, status } = userData;
    
    try {
      // 检查邮箱是否已存在
      const existingUser = await ctx.model.UserModel.findOne({
        where: { email }
      });
      
      if (existingUser) {
        throw new Error('邮箱已存在');
      }
      
      // 创建用户
      const user = await ctx.model.UserModel.create({
        name,
        email,
        password, // 注意：实际应用中需要加密密码
        role,
        status: status || 'active'
      });
      
      return {
        id: user.id
      };
    } catch (error) {
      ctx.logger.error('创建用户业务逻辑执行失败:', error);
      throw new Error(`创建用户业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 更新用户
  async updateUser(id, userData) {
    const { ctx } = this;
    const { name, email, password, role, status } = userData;
    
    try {
      const user = await ctx.model.UserModel.findByPk(id);
      
      if (!user) {
        throw new Error('用户不存在');
      }
      
      // 检查邮箱是否已存在（排除当前用户）
      if (email && email !== user.email) {
        const existingUser = await ctx.model.UserModel.findOne({
          where: { 
            email,
            id: {
              [ctx.app.Sequelize.Op.ne]: id
            }
          }
        });
        
        if (existingUser) {
          throw new Error('邮箱已存在');
        }
      }
      
      // 更新用户
      const updateData = {};
      if (name !== undefined) updateData.name = name;
      if (email !== undefined) updateData.email = email;
      // 只有当密码不为空时才更新密码
      if (password !== undefined && password !== null && password !== '') {
        updateData.password = password; // 注意：实际应用中需要加密密码
      }
      if (role !== undefined) updateData.role = role;
      if (status !== undefined) updateData.status = status;
      
      await user.update(updateData);
      
      return {
        id: user.id
      };
    } catch (error) {
      ctx.logger.error('更新用户业务逻辑执行失败:', error);
      throw new Error(`更新用户业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 删除用户
  async deleteUser(id) {
    const { ctx } = this;
    
    try {
      const user = await ctx.model.UserModel.findByPk(id);
      
      if (!user) {
        throw new Error('用户不存在');
      }
      
      // 禁止删除管理员用户
      if (user.role === 'admin') {
        throw new Error('不能删除管理员用户');
      }
      
      await user.destroy();
      
      return true;
    } catch (error) {
      ctx.logger.error('删除用户业务逻辑执行失败:', error);
      throw new Error(`删除用户业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 批量删除用户
  async batchDeleteUsers(ids) {
    const { ctx } = this;
    
    try {
      // 检查用户是否存在
      const users = await ctx.model.UserModel.findAll({
        where: {
          id: ids
        }
      });
      
      // 检查是否有管理员用户
      const adminUsers = users.filter(user => user.role === 'admin');
      if (adminUsers.length > 0) {
        throw new Error('不能删除管理员用户');
      }
      
      // 批量删除用户
      await ctx.model.UserModel.destroy({
        where: {
          id: ids
        }
      });
      
      return true;
    } catch (error) {
      ctx.logger.error('批量删除用户业务逻辑执行失败:', error);
      throw new Error(`批量删除用户业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 批量更新用户状态
  async batchUpdateUserStatus(ids, status) {
    const { ctx } = this;
    
    try {
      // 检查用户是否存在
      const users = await ctx.model.UserModel.findAll({
        where: {
          id: ids
        }
      });
      
      // 检查是否有管理员用户
      const adminUsers = users.filter(user => user.role === 'admin');
      if (adminUsers.length > 0 && status !== 'active') {
        throw new Error('不能禁用管理员用户');
      }
      
      // 批量更新用户状态
      await ctx.model.UserModel.update(
        { status },
        {
          where: {
            id: ids
          }
        }
      );
      
      return true;
    } catch (error) {
      ctx.logger.error('批量更新用户状态业务逻辑执行失败:', error);
      throw new Error(`批量更新用户状态业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // ==================== 角色权限 ====================
  
  // 获取角色列表
  async getRoles(queryParams) {
    const { ctx } = this;
    const { page = 1, limit = 20, name } = queryParams;
    
    try {
      // 构建查询条件
      const whereClause = {};
      
      if (name) {
        whereClause.name = {
          [ctx.app.Sequelize.Op.like]: `%${name}%`
        };
      }
      
      // 查询数据
      const result = await ctx.model.RoleModel.findAndCountAll({
        where: whereClause,
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit)
      });
      
      // 转换数据格式
      const roles = result.rows.map(role => ({
        id: role.id,
        name: role.name,
        description: role.description,
        permissions: role.permissions,
        createdAt: role.createdAt,
        updatedAt: role.updatedAt
      }));
      
      return {
        list: roles,
        pagination: {
          total: result.count,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      };
    } catch (error) {
      ctx.logger.error('获取角色列表业务逻辑执行失败:', error);
      throw new Error(`获取角色列表业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 获取角色详情
  async getRole(id) {
    const { ctx } = this;
    
    try {
      const role = await ctx.model.RoleModel.findByPk(id);
      
      if (!role) {
        throw new Error('角色不存在');
      }
      
      return {
        id: role.id,
        name: role.name,
        description: role.description,
        permissions: role.permissions,
        createdAt: role.createdAt,
        updatedAt: role.updatedAt
      };
    } catch (error) {
      ctx.logger.error('获取角色详情业务逻辑执行失败:', error);
      throw new Error(`获取角色详情业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 创建角色
  async createRole(roleData) {
    const { ctx } = this;
    const { name, description, permissions } = roleData;
    
    try {
      // 检查角色名称是否已存在
      const existingRole = await ctx.model.RoleModel.findOne({
        where: { name }
      });
      
      if (existingRole) {
        throw new Error('角色名称已存在');
      }
      
      // 创建角色
      const role = await ctx.model.RoleModel.create({
        name,
        description,
        permissions: permissions || []
      });
      
      return {
        id: role.id
      };
    } catch (error) {
      ctx.logger.error('创建角色业务逻辑执行失败:', error);
      throw new Error(`创建角色业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 更新角色
  async updateRole(id, roleData) {
    const { ctx } = this;
    const { name, description, permissions } = roleData;
    
    try {
      const role = await ctx.model.RoleModel.findByPk(id);
      
      if (!role) {
        throw new Error('角色不存在');
      }
      
      // 检查角色名称是否已存在（排除当前角色）
      if (name && name !== role.name) {
        const existingRole = await ctx.model.RoleModel.findOne({
          where: { 
            name,
            id: {
              [ctx.app.Sequelize.Op.ne]: id
            }
          }
        });
        
        if (existingRole) {
          throw new Error('角色名称已存在');
        }
      }
      
      // 更新角色
      const updateData = {};
      if (name !== undefined) updateData.name = name;
      if (description !== undefined) updateData.description = description;
      if (permissions !== undefined) updateData.permissions = permissions;
      
      await role.update(updateData);
      
      return {
        id: role.id
      };
    } catch (error) {
      ctx.logger.error('更新角色业务逻辑执行失败:', error);
      throw new Error(`更新角色业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 删除角色
  async deleteRole(id) {
    const { ctx } = this;
    
    try {
      ctx.logger.info('开始删除角色，ID:', id);
      
      const role = await ctx.model.RoleModel.findByPk(id);
      
      if (!role) {
        throw new Error('角色不存在');
      }
      
      ctx.logger.info('找到角色:', role.name);
      
      // 禁止删除管理员角色
      if (role.name === '管理员') {
        throw new Error('不能删除管理员角色');
      }
      
      // 检查是否有用户使用该角色
      const userCount = await ctx.model.UserModel.count({
        where: {
          role: role.name
        }
      });
      
      ctx.logger.info('使用该角色的用户数量:', userCount);
      
      if (userCount > 0) {
        throw new Error(`有${userCount}个用户正在使用该角色，不能删除`);
      }
      
      await role.destroy();
      
      ctx.logger.info('角色删除成功');
      return true;
    } catch (error) {
      ctx.logger.error('删除角色业务逻辑执行失败:', error);
      throw new Error(`删除角色业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // ==================== 操作日志 ====================
  
  // 获取操作日志列表
  async getOperationLogs(queryParams) {
    const { ctx } = this;
    const { 
      page = 1, 
      limit = 20, 
      userId, 
      action, 
      module,
      startDate,
      endDate
    } = queryParams;
    
    try {
      // 构建查询条件
      const whereClause = {};
      
      if (userId) {
        whereClause.userId = userId;
      }
      
      if (action) {
        whereClause.action = action;
      }
      
      if (module) {
        whereClause.module = module;
      }
      
      if (startDate || endDate) {
        whereClause.createdAt = {};
        if (startDate) {
          whereClause.createdAt[ctx.app.Sequelize.Op.gte] = new Date(startDate);
        }
        if (endDate) {
          whereClause.createdAt[ctx.app.Sequelize.Op.lte] = new Date(endDate);
        }
      }
      
      // 查询数据
      const result = await ctx.model.OperationLogModel.findAndCountAll({
        where: whereClause,
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit)
      });
      
      // 转换数据格式
      const logs = result.rows.map(log => ({
        id: log.id,
        userId: log.userId,
        action: log.action,
        module: log.module,
        description: log.description,
        ip: log.ip,
        userAgent: log.userAgent,
        createdAt: log.createdAt,
        updatedAt: log.updatedAt
      }));
      
      return {
        list: logs,
        pagination: {
          total: result.count,
          page: parseInt(page),
          limit: parseInt(limit)
        }
      };
    } catch (error) {
      ctx.logger.error('获取操作日志列表业务逻辑执行失败:', error);
      throw new Error(`获取操作日志列表业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 获取操作日志详情
  async getOperationLog(id) {
    const { ctx } = this;
    
    try {
      const log = await ctx.model.OperationLogModel.findByPk(id);
      
      if (!log) {
        throw new Error('操作日志不存在');
      }
      
      return {
        id: log.id,
        userId: log.userId,
        action: log.action,
        module: log.module,
        description: log.description,
        ip: log.ip,
        userAgent: log.userAgent,
        createdAt: log.createdAt,
        updatedAt: log.updatedAt
      };
    } catch (error) {
      ctx.logger.error('获取操作日志详情业务逻辑执行失败:', error);
      throw new Error(`获取操作日志详情业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 删除操作日志
  async deleteOperationLog(id) {
    const { ctx } = this;
    
    try {
      const log = await ctx.model.OperationLogModel.findByPk(id);
      
      if (!log) {
        throw new Error('操作日志不存在');
      }
      
      await log.destroy();
      
      return true;
    } catch (error) {
      ctx.logger.error('删除操作日志业务逻辑执行失败:', error);
      throw new Error(`删除操作日志业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // ==================== 系统设置 ====================
  
  // 获取系统设置
  async getSystemSettings() {
    const { ctx } = this;
    
    try {
      // 这里可以从数据库或其他配置源获取系统设置
      // 暂时返回默认设置
      return {
        basicSettings: {
          systemInfo: {
            name: '小采灵犀智能对账系统',
            description: '基于AI技术的智能对账平台',
            version: 'v1.0.0',
            copyright: '© 2023 小采科技有限公司'
          },
          systemBehavior: {
            autoSave: true,
            autoRefresh: false,
            refreshInterval: 60,
            theme: 'light'
          }
        },
        securitySettings: {
          passwordPolicy: {
            minLength: 8,
            requireNumber: true,
            requireSpecialChar: true,
            expirationDays: 90
          },
          loginSecurity: {
            lockOnFailedAttempts: true,
            maxFailedAttempts: 5,
            lockDuration: 30
          },
          notifications: {
            loginNotification: true,
            suspiciousLoginAlert: true,
            passwordChangeNotification: true,
            securityEventNotification: true,
            notificationMethods: ['email', 'system']
          }
        },
        networkSettings: {
          api: {
            timeout: 5000,
            retryCount: 3,
            rateLimiting: true,
            requestsPerMinute: 1000
          },
          proxy: {
            enabled: false,
            host: '',
            port: 8080,
            authType: 'none',
            username: '',
            password: ''
          }
        },
        dataSettings: {
          backup: {
            autoBackup: true,
            frequency: 'daily',
            keepBackups: 30,
            backupPath: '/backups'
          },
          cleanup: {
            autoCleanupLogs: true,
            logRetentionDays: 30,
            autoCleanupCache: true,
            cacheRetentionDays: 7
          }
        }
      };
    } catch (error) {
      ctx.logger.error('获取系统设置业务逻辑执行失败:', error);
      throw new Error(`获取系统设置业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 更新系统设置
  async updateSystemSettings(settings) {
    const { ctx } = this;
    
    try {
      // 这里可以将系统设置保存到数据库或其他配置源
      // 暂时只是简单处理
      ctx.logger.info('系统设置已更新:', settings);
      return true;
    } catch (error) {
      ctx.logger.error('更新系统设置业务逻辑执行失败:', error);
      throw new Error(`更新系统设置业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // ==================== 快捷键设置 ====================
  
  // 获取用户快捷键设置
  async getUserShortcuts(userId) {
    const { ctx } = this;
    
    try {
      const shortcuts = await ctx.model.UserShortcutModel.findAll({
        where: { userId }
      });
      
      return shortcuts;
    } catch (error) {
      ctx.logger.error('获取用户快捷键设置业务逻辑执行失败:', error);
      throw new Error(`获取用户快捷键设置业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 更新用户快捷键设置
  async updateUserShortcuts(userId, shortcuts) {
    const { ctx } = this;
    
    try {
      // 删除用户现有的快捷键设置
      await ctx.model.UserShortcutModel.destroy({
        where: { userId }
      });
      
      // 批量创建新的快捷键设置
      const shortcutData = shortcuts.map(shortcut => ({
        ...shortcut,
        userId
      }));
      
      await ctx.model.UserShortcutModel.bulkCreate(shortcutData);
      
      return true;
    } catch (error) {
      ctx.logger.error('更新用户快捷键设置业务逻辑执行失败:', error);
      throw new Error(`更新用户快捷键设置业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // ==================== 用户分组 ====================
  
  // 获取所有用户分组
  async getUserGroups() {
    const { ctx } = this;
    
    try {
      const groups = await ctx.model.UserGroupModel.findAll({
        order: [['createdAt', 'DESC']]
      });
      
      // 获取每个分组的成员数量
      const groupIds = groups.map(group => group.id);
      const memberCounts = {};
      
      if (groupIds.length > 0) {
        const members = await ctx.model.UserGroupMemberModel.findAll({
          where: {
            groupId: groupIds
          },
          attributes: [
            'groupId',
            [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count']
          ],
          group: ['groupId']
        });
        
        members.forEach(member => {
          memberCounts[member.groupId] = parseInt(member.get('count'));
        });
      }
      
      return groups.map(group => ({
        id: group.id,
        name: group.name,
        description: group.description,
        memberCount: memberCounts[group.id] || 0,
        createdAt: group.createdAt,
        updatedAt: group.updatedAt
      }));
    } catch (error) {
      ctx.logger.error('获取用户分组业务逻辑执行失败:', error);
      throw new Error(`获取用户分组业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 创建用户分组
  async createUserGroup(groupData) {
    const { ctx } = this;
    const { name, description } = groupData;
    
    try {
      // 检查分组名称是否已存在
      const existingGroup = await ctx.model.UserGroupModel.findOne({
        where: { name }
      });
      
      if (existingGroup) {
        throw new Error('分组名称已存在');
      }
      
      // 创建分组
      const group = await ctx.model.UserGroupModel.create({
        name,
        description
      });
      
      return {
        id: group.id
      };
    } catch (error) {
      ctx.logger.error('创建用户分组业务逻辑执行失败:', error);
      throw new Error(`创建用户分组业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 更新用户分组
  async updateUserGroup(id, groupData) {
    const { ctx } = this;
    const { name, description } = groupData;
    
    try {
      const group = await ctx.model.UserGroupModel.findByPk(id);
      
      if (!group) {
        throw new Error('分组不存在');
      }
      
      // 检查分组名称是否已存在（排除当前分组）
      if (name && name !== group.name) {
        const existingGroup = await ctx.model.UserGroupModel.findOne({
          where: { 
            name,
            id: {
              [ctx.app.Sequelize.Op.ne]: id
            }
          }
        });
        
        if (existingGroup) {
          throw new Error('分组名称已存在');
        }
      }
      
      // 更新分组
      const updateData = {};
      if (name !== undefined) updateData.name = name;
      if (description !== undefined) updateData.description = description;
      
      await group.update(updateData);
      
      return {
        id: group.id
      };
    } catch (error) {
      ctx.logger.error('更新用户分组业务逻辑执行失败:', error);
      throw new Error(`更新用户分组业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 删除用户分组
  async deleteUserGroup(id) {
    const { ctx } = this;
    
    try {
      const group = await ctx.model.UserGroupModel.findByPk(id);
      
      if (!group) {
        throw new Error('分组不存在');
      }
      
      // 删除分组成员关联
      await ctx.model.UserGroupMemberModel.destroy({
        where: { groupId: id }
      });
      
      // 删除分组
      await group.destroy();
      
      return true;
    } catch (error) {
      ctx.logger.error('删除用户分组业务逻辑执行失败:', error);
      throw new Error(`删除用户分组业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 获取分组成员
  async getGroupMembers(groupId) {
    const { ctx } = this;
    
    try {
      const members = await ctx.model.UserGroupMemberModel.findAll({
        where: { groupId },
        include: [{
          model: ctx.model.UserModel,
          as: 'user',
          attributes: ['id', 'name', 'email', 'role', 'status']
        }]
      });
      
      return members.map(member => ({
        id: member.id,
        userId: member.userId,
        groupId: member.groupId,
        user: member.user ? {
          id: member.user.id,
          name: member.user.name,
          email: member.user.email,
          role: member.user.role,
          status: member.user.status
        } : null,
        createdAt: member.createdAt
      }));
    } catch (error) {
      ctx.logger.error('获取分组成员业务逻辑执行失败:', error);
      throw new Error(`获取分组成员业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 添加用户到分组
  async addUserToGroup(userId, groupId) {
    const { ctx } = this;
    
    try {
      // 检查用户和分组是否存在
      const user = await ctx.model.UserModel.findByPk(userId);
      const group = await ctx.model.UserGroupModel.findByPk(groupId);
      
      if (!user) {
        throw new Error('用户不存在');
      }
      
      if (!group) {
        throw new Error('分组不存在');
      }
      
      // 检查用户是否已在分组中
      const existingMember = await ctx.model.UserGroupMemberModel.findOne({
        where: { userId, groupId }
      });
      
      if (existingMember) {
        throw new Error('用户已在该分组中');
      }
      
      // 添加用户到分组
      const member = await ctx.model.UserGroupMemberModel.create({
        userId,
        groupId
      });
      
      return {
        id: member.id
      };
    } catch (error) {
      ctx.logger.error('添加用户到分组业务逻辑执行失败:', error);
      throw new Error(`添加用户到分组业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 从分组中移除用户
  async removeUserFromGroup(userId, groupId) {
    const { ctx } = this;
    
    try {
      // 检查关联是否存在
      const member = await ctx.model.UserGroupMemberModel.findOne({
        where: { userId, groupId }
      });
      
      if (!member) {
        throw new Error('用户不在该分组中');
      }
      
      // 删除关联
      await member.destroy();
      
      return true;
    } catch (error) {
      ctx.logger.error('从分组中移除用户业务逻辑执行失败:', error);
      throw new Error(`从分组中移除用户业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // ==================== UI配置 ====================
  
  // 获取UI配置
  async getUIConfig(userId, pageKey) {
    const { ctx } = this;
    
    try {
      const config = await ctx.model.UIConfigModel.findOne({
        where: { 
          userId,
          pageKey
        }
      });
      
      return config ? config.config : {};
    } catch (error) {
      ctx.logger.error('获取UI配置业务逻辑执行失败:', error);
      throw new Error(`获取UI配置业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 保存UI配置
  async saveUIConfig(userId, pageKey, config) {
    const { ctx } = this;
    
    try {
      // 查找现有的配置
      let uiConfig = await ctx.model.UIConfigModel.findOne({
        where: { 
          userId,
          pageKey
        }
      });
      
      if (uiConfig) {
        // 更新现有配置
        await uiConfig.update({ config });
      } else {
        // 创建新配置
        await ctx.model.UIConfigModel.create({
          userId,
          pageKey,
          config
        });
      }
      
      return true;
    } catch (error) {
      ctx.logger.error('保存UI配置业务逻辑执行失败:', error);
      throw new Error(`保存UI配置业务逻辑执行失败: ${error.message}`);
    }
  }
  
  // 删除UI配置
  async deleteUIConfig(userId, pageKey) {
    const { ctx } = this;
    
    try {
      await ctx.model.UIConfigModel.destroy({
        where: { 
          userId,
          pageKey
        }
      });
      
      return true;
    } catch (error) {
      ctx.logger.error('删除UI配置业务逻辑执行失败:', error);
      throw new Error(`删除UI配置业务逻辑执行失败: ${error.message}`);
    }
  }
}

module.exports = SystemService;